#pragma once

#include <iostream>
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>

#include "Log.hpp"

class sock
{
public:
    static const int gbacklog = 20;

    static int Socket()
    {
        // 1. 创建套接字
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            logMessage(FATAL, "socket:%s[%d]", strerror(errno), sockfd);
            exit(SOCK_ERR);
        }

        return sockfd;
    }

    static void Bind(int socket, uint16_t port)
    {
        // 2.填充域
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        // 3. 绑定网络信息
        if (bind(socket, (const struct sockaddr *)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "bind:%s[%d]", strerror(errno), socket);
            exit(BIND_ERR);
        }
        logMessage(DEBUG, "bind success...");
    }

    static void Listen(int socket)
    {
        // 4. 监听套接字
        if (listen(socket, gbacklog) < 0)
        {
            logMessage(FATAL, "listen:%s[%d]", strerror(errno), socket);
            exit(LISTEN_ERR);
        }
        logMessage(DEBUG, "listen success...");
    }

    static int Accept(int socket, std::string *clientip, uint16_t *clientport)
    {
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);

        int sockfd = accept(socket, (struct sockaddr *)&peer, &len);
        if (sockfd < 0)
        {
            // 获取链接失败
            logMessage(WARINING, "accept: %s[%d]", strerror(errno), sockfd);
        }

        if(clientport) *clientport = ntohs(peer.sin_port);
        if(clientip) *clientip = inet_ntoa(peer.sin_addr);
        return sockfd;
    }
};